package com.alibaba.citrus.cr.mn.order.center.facade.function.assemble.impl.exchangeorder;

import com.alibaba.citrus.cr.common.enums.ordercenter.SalesOrgTypeEnum;
import com.alibaba.citrus.cr.mn.order.center.facade.adapter.dataobject.response.ItemSearchAbilityDTO;
import com.alibaba.citrus.cr.mn.order.center.facade.adapter.dataobject.response.SalesBizOrgQueryDTO;
import com.alibaba.citrus.cr.mn.order.center.facade.function.assemble.OrderBizAssemble;
import com.alibaba.citrus.cr.mn.order.center.forecastorder.ability.NormalPriceQueryUtils;
import com.alibaba.cz.base.tool.log.Log;
import com.alibaba.fastjson.JSON;
import com.alibaba.lattice2.epoch.sdk.model.Result;
import com.epoch.app.crforecastsales.model.dto.SubOrderInfo;
import com.epoch.app.crforecastsales.sdo.MainOrderInfo;
import com.epoch.app.mnordercenter.model.dto.ExchangeOrderBizCreateRequest;
import com.epoch.app.mnordercenter.model.dto.ExchangeOrderLineAtomCreateRequest;
import com.epoch.app.mnordercenter.model.dto.PolicyPriceMainRequest;
import com.epoch.app.mnordercenter.model.dto.PolicyPriceQueryRequest;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author zhangxiaorui
 * @ClassName OrderBizAssembleOfStrategyCenter
 * @description: TODO
 * @date 2023/05/17 09:53
 * @version: 1.0
 */
@Service
@Order(5)
public class ExchangeOrderBizAssembleOfCostCenter implements OrderBizAssemble<ExchangeOrderBizCreateRequest> {

    private static final Log log = Log.getLogger(ExchangeOrderBizAssembleOfCostCenter.class);

    @Resource
    private NormalPriceQueryUtils normalPriceQueryUtils;

    @Override
    public Map<String, Object> query(ExchangeOrderBizCreateRequest salesOrderBizBatchCreateRequest) {
        Map<String, Object> result = Maps.newHashMap();

        result.put(String.format("costCenterCode_%s", "XA"), String.format("costCenterName_%s", "XA"));

        return result;
    }

    @Override
    public Map<String, Object> query(List<ExchangeOrderBizCreateRequest> orderBizCreateRequests) {
        return Maps.newHashMap();
    }

    @Override
    public Result<String> assemble(Map<String, Object> queryResponseMap, ExchangeOrderBizCreateRequest createRequest) {

        Map<String, PolicyPriceQueryRequest> subOrderPriceMap = queryGoodsDetailPrice(createRequest, queryResponseMap);

        for (ExchangeOrderLineAtomCreateRequest orderDetail : createRequest.getOrderDetails()) {
            String priceLineKey = orderDetail.getProductCode() + "-" + orderDetail.getSalesUnitCode();
            PolicyPriceQueryRequest subOrderInfo = subOrderPriceMap.get(priceLineKey);
            if (Objects.isNull(subOrderInfo) || Objects.isNull(subOrderInfo.getUnitPrice()) || subOrderInfo.getUnitPrice() < 0L) {
                return Result.fail(createRequest.getSourceOrderNo(),"OC-01-001-01-16-023", "价格格式错误");
            }
            Long unitPrice = subOrderInfo.getUnitPrice();
            BigDecimal unitPriceNYC = new BigDecimal(String.valueOf(unitPrice)).divide(new BigDecimal("100"), 2, RoundingMode.HALF_UP);
            orderDetail.setUnitPrice(unitPriceNYC.toPlainString());

            if(StringUtils.isBlank(orderDetail.getProductQuantity())) {
                continue;
            }
            Long totalAmount = unitPrice * Long.parseLong(orderDetail.getProductQuantity());
            BigDecimal totalAmountNYC = new BigDecimal(String.valueOf(totalAmount)).divide(new BigDecimal("100"), 2, RoundingMode.HALF_UP);

            // 常规总金额
            orderDetail.setTotalAmount(totalAmountNYC.toPlainString());
            // 手工总金额/数量 = 手工单价
            if(StringUtils.isNotBlank(orderDetail.getManualTotalAmount())) {
                BigDecimal manualPrice = new BigDecimal(orderDetail.getManualTotalAmount())
                        .divide(new BigDecimal(orderDetail.getProductQuantity()),2, RoundingMode.HALF_UP);
                orderDetail.setManualPrice(manualPrice.toPlainString());
            }
        }

        return Result.success(null);
    }

//    private Map<String, SubOrderInfo> queryGoodsDetailPrice(ExchangeOrderBizCreateRequest request, Map<String, Object> queryResponseMap) {
//        MainOrderInfo mainOrderInfo = convertMainOrder(request, queryResponseMap);
//        mainOrderInfo.setForecastOrderLineSDOList(convertOrderLine(request.getOrderDetails(), queryResponseMap));
//
//        QueryGoodsDetailRequest queryGoodsDetailResponseRequest = new QueryGoodsDetailRequest();
//        queryGoodsDetailResponseRequest.setForecastOrderSDO(mainOrderInfo);
//        List<SubOrderInfo> subOrders = normalPriceQueryUtils.queryGoodsDetail(queryGoodsDetailResponseRequest);
//        log.info("ExchangeOrderBizAssembleOfCostCenter#queryGoodsDetailPrice request: {}, subOrders: {}",
//                JSON.toJSONString(queryGoodsDetailResponseRequest), JSONArray.toJSONString(subOrders));
//        return Optional.ofNullable(subOrders).orElse(Lists.newArrayList())
//                .stream().collect(Collectors.toMap(SubOrderInfo::getSourceLineNum, p -> p, (v1, v2) -> v1));
//    }

    private Map<String, PolicyPriceQueryRequest> queryGoodsDetailPrice(ExchangeOrderBizCreateRequest request, Map<String, Object> queryResponseMap) {
        PolicyPriceMainRequest priceMainRequest = convertPriceMainOrder(request);

        log.info("ExchangeOrderBizAssembleOfCostCenter#queryGoodsDetailPrice priceMainRequest: {} priceMainRequest: {}",
                priceMainRequest);
        List<PolicyPriceQueryRequest> policyPriceQueryRequests = normalPriceQueryUtils.queryPolicyPrice(priceMainRequest);
        log.info("ExchangeOrderBizAssembleOfCostCenter#queryGoodsDetailPrice policyPriceQueryRequests: {}", policyPriceQueryRequests);
        return Optional.ofNullable(policyPriceQueryRequests).orElse(Lists.newArrayList())
                .stream().collect(Collectors.toMap(o -> o.getMaterialCode()+"-"+o.getSalesUnitCode(), p -> p, (v1, v2) -> v1));
    }

    private PolicyPriceMainRequest convertPriceMainOrder(ExchangeOrderBizCreateRequest request) {
        log.info("=============convertMainOrder_request:" + JSON.toJSON(request));
        PolicyPriceMainRequest mainOrderInfo = new PolicyPriceMainRequest();
        mainOrderInfo.setFromSys(request.getFromSys());
        mainOrderInfo.setSalesOrganizationCode(request.getSalesOrganizationCode());
        mainOrderInfo.setBusinessType(request.getBusinessType());

        log.info("=============convertMainOrder_mainOrderInfo:" + JSON.toJSON(mainOrderInfo));
        mainOrderInfo.setCalculateItemList(convertPriceOrderLine(request.getOrderDetails(),request));
        return mainOrderInfo;    }

    private List<PolicyPriceQueryRequest> convertPriceOrderLine(List<ExchangeOrderLineAtomCreateRequest> orderDetails, ExchangeOrderBizCreateRequest request) {
        if (CollectionUtils.isEmpty(orderDetails)) {
            return Lists.newArrayList();
        }
        List<PolicyPriceQueryRequest> responses = Lists.newArrayList();
        for (ExchangeOrderLineAtomCreateRequest orderLine : orderDetails) {
            if (StringUtils.isNotBlank(orderLine.getProductCode())) {
                PolicyPriceQueryRequest response = PolicyPriceQueryRequest.builder()
                        .priceTypeCode("ZP01")
                        .orgSalesOrganizationCode(request.getSalesOrganizationCode())
                        .channelCode(request.getBusinessChannel())
                        .scItemGroupCode(request.getProductGroupCode())
                        .customerCode(request.getCustomerCode())
                        .customerSaleAddressCode(request.getCustomerCode())
                        .customerSendAddressCode(request.getShipToPartyCode())
                        .salesUnitCode(orderLine.getSalesUnitCode())
                        .materialCode(orderLine.getProductCode())
//                .salesArea(orderLine.getsa())
//                .customerGroup(orderLine.getUnitPrice())
                        .departmentCode(request.getSalesDepartmentCode())
//                .salesGroupCode(forecastOrder.getProductGroupCode())
                        .factoryCode(orderLine.getDeliveryFactoryCode())
                        .storePlace(orderLine.getStockCode())
//                .priceListCode(orderLine.getUnitPrice())
//                        .unitPrice(orderLine.getUnitPrice())
                        .build();
                responses.add(response);
            }
        }
        return responses;
    }

    private MainOrderInfo convertMainOrder(ExchangeOrderBizCreateRequest exchangeOrderBizCreateRequest, Map<String, Object> queryResponseMap) {
        // 销售组织、组织部门 等架构查询
        Map<String, SalesBizOrgQueryDTO> salesOrgByCodeMap = getBizInfoMap(queryResponseMap, SALES_ORGANIZATION, SalesBizOrgQueryDTO.class);

        MainOrderInfo mainOrderInfo=new MainOrderInfo();
        mainOrderInfo.setCustomerName(exchangeOrderBizCreateRequest.getCustomerName());
        mainOrderInfo.setCustomerCode(exchangeOrderBizCreateRequest.getCustomerCode());
        mainOrderInfo.setReceiveAddressCode(exchangeOrderBizCreateRequest.getShipToPartyCode());
        mainOrderInfo.setProductGroupCode(exchangeOrderBizCreateRequest.getProductGroupCode());
        mainOrderInfo.setChannelCode(exchangeOrderBizCreateRequest.getBusinessChannel());
        if(StringUtils.isNotBlank(exchangeOrderBizCreateRequest.getSalesDepartmentCode())) {
            mainOrderInfo.setDepartmentCode(String.valueOf(salesOrgByCodeMap.get(exchangeOrderBizCreateRequest.getSalesDepartmentCode()).getId()));
        }
        mainOrderInfo.setOrganizationCode(String.valueOf(salesOrgByCodeMap.get(SalesOrgTypeEnum.SALES_ORG.getCode() + "_" + exchangeOrderBizCreateRequest.getSalesOrganizationCode()).getId()));
        return mainOrderInfo;
    }

    private List<SubOrderInfo> convertOrderLine(List<ExchangeOrderLineAtomCreateRequest> orderLines, Map<String, Object> queryResponseMap) {
        if (CollectionUtils.isEmpty(orderLines)) {
            return Lists.newArrayList();
        }
        // 物料
        Map<String, ItemSearchAbilityDTO> scItemInfoMap = getBizInfoMap(queryResponseMap, SC_ITEM_INFO, ItemSearchAbilityDTO.class);

        List<SubOrderInfo> responses = Lists.newArrayList();
        for (ExchangeOrderLineAtomCreateRequest orderLine : orderLines) {
            SubOrderInfo response = SubOrderInfo.builder()
                    .detailRemark(orderLine.getNote())
                    .scItemId(scItemInfoMap.get(orderLine.getProductCode()).getScItemId())
                    .goodsCode(orderLine.getProductCode())
                    .scItemTitle(orderLine.getProductName())
                    .saleUnitCode(orderLine.getSalesUnitCode())
                    .saleUnit(orderLine.getSalesUnitName())
                    .unitConvert(orderLine.getUnitConversionRelationship())
                    .sourceLineNum(orderLine.getSourceLineNum())
                    .inventoryUnitCode(orderLine.getStockUnitCode())
                    .inventoryUnit(orderLine.getStockUnitName())
                    .build();
            responses.add(response);
        }
        return responses;
    }
}
